import React, { useState, useEffect } from 'react'
import { View, Text, Swiper, SwiperItem } from '@tarojs/components'
import { weekDays, getSwipeGroup, getArrAdj, getWeekCalendar, swapperArr } from './helper'
import './style.less'
import dayjs from 'dayjs';
import dshUtils from 'dsh-utils';

export default (props) => {
  const [activeDay, setActiveDay] = useState(props.currentDate); //当前高亮的天
  const [swipeGroup, setSwipeGroup] = useState([getWeekCalendar(props.currentDate, -1), getWeekCalendar(props.currentDate, 0), getWeekCalendar(props.currentDate, 1)]); // swapper内容(3个周板面)
  const [swipeIndex, setSwipeIndex] = useState(1); //当前swipeIndex
  const [clickArrowType, setClickArrowType] = useState('');
  useEffect(() => {
    syncSwipeGroup('haveCurrentDate');
    setActiveDay(props.currentDate)
  }, [props.currentDate])

  const setActiveDayFn = (val) => {
    props.onCsSelectDate(val);
    setActiveDay(val)
  }
  // 设置swapper内容
  const syncSwipeGroup = (current = swipeIndex, isTouch) => { // 点击和触摸和默认props初始化 3种情况 要不同对待，不要问我为啥，太他妈复杂了
    if (isTouch) {
      const res = getSwipeGroup(swipeGroup, current);
      setSwipeGroup([...res])
    } else {
      if (current === 'haveCurrentDate') {
        const res = getSwipeGroup(swipeGroup, swipeIndex, props.currentDate);
        setSwipeGroup([...res])
      } else {
        const res = getSwipeGroup(swipeGroup, current);
        setSwipeGroup([...res])
      }

    }
  }

  // 天点击事件
  const dayClick = (val) => {
    setActiveDayFn(val);
  }

  // 日历current变化事件
  const swiperChange = (val) => {
    const { current, source } = val.detail;
    if (source === 'touch') { // touch为滑动，否则为点击直接改变index
      setSwipeIndex(current)

      const isLeftAction = dshUtils.isLeftSlide({ arr: swapperArr, oldIndex: swipeIndex, newIndex: current })
      const swipeType = isLeftAction ? 'next' : 'prev'

      // 更新当前激活的day，即下一周的这天也要高亮
      const afterDay = getActiveDay(swipeType);
      setActiveDayFn(afterDay);

      syncSwipeGroup(current, true) // 一旦变化就应该更新日历元素据，即swipeGroup
    } else {
      // 更新当前激活的day，即下一周的这天也要高亮
      const afterDay = getActiveDay(clickArrowType);
      setActiveDayFn(afterDay);
      syncSwipeGroup(current) // 一旦变化就应该更新日历元素据，即swipeGroup
    }
  }

  // 更新当前active Day（比如在点击箭头或者滑动的时候触发）
  const getActiveDay = (val) => {
    // 更新当前激活的day，即下一周的这天也要高亮
    const fnName = val === 'prev' ? 'subtract' : 'add';
    const afterDay = dayjs(activeDay)[fnName](7, 'day');
    return afterDay;
  }


  // 箭头点击事件
  const arrowClick = (val) => {
    // 设置swiperIndex+1，即切换下一个swiperItem
    const nextSwiperIndex = getArrAdj(swipeIndex, val);
    setSwipeIndex(nextSwiperIndex);
    setClickArrowType(val);
  }

  return (<View className="cs-calendar">
    {/* 头部title */}
    <View className='at-calendar__controller controller'>
      <View className='controller__arrow controller__arrow--left' onClick={() => { arrowClick('prev') }} />
      <Text className='controller__info'>
        {dayjs(activeDay).format('YYYY年MM月')}
      </Text>
      <View className='controller__arrow controller__arrow--right' onClick={() => { arrowClick('next') }} />
    </View>

    {/* 渲染周 */}
    <View className="week-days">
      {weekDays.map(item => (<View className="week-day">{item}</View>))}
    </View>

    {/* 渲染天 */}
    <Swiper className="my-swiper" circular current={swipeIndex} onChange={swiperChange}>
      {swipeGroup.map((week, index) => {
        return <SwiperItem className="my-swiper-item" key={index}>
          {week.map((day, index) => {
            const isCurrenDay = dayjs(activeDay).isSame(day, 'day');
            const classNames = ["day", isCurrenDay ? 'selected' : '']
            return <View key={index} className={classNames} onClick={() => { dayClick(day) }}>{dayjs(day).format('D')}</View>
          })}
        </SwiperItem>
      })}
    </Swiper>
  </View>)
}